<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/css/all.min.css" integrity="sha256-mUZM63G8m73Mcidfrv5E+Y61y7a12O5mW4ezU3bxqW4=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"tallgy.gitee.io","root":"/","images":"/images","scheme":"Muse","darkmode":false,"version":"8.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}}</script><script src="/js/config.js"></script>
<meta name="description" content="JavaScript 迭代器1https:&#x2F;&#x2F;developer.mozilla.org&#x2F;zh-CN&#x2F;docs&#x2F;Web&#x2F;JavaScript&#x2F;Guide&#x2F;Iterators_and_Generators    ​        首先JavaScript里面的数组我们可以知道其实也是一个对象。但是为什么我们可以通过一些方法进行循环，这里就运用到了一个迭代器的方法。iterator 可迭代协议​">
<meta property="og:type" content="article">
<meta property="og:title" content="迭代器">
<meta property="og:url" content="http://tallgy.gitee.io/2021/11/14/JavaScript/%E9%9A%8F%E7%AC%94/%E8%BF%AD%E4%BB%A3%E5%99%A8/index.html">
<meta property="og:site_name" content="tallgy&#39;s blog">
<meta property="og:description" content="JavaScript 迭代器1https:&#x2F;&#x2F;developer.mozilla.org&#x2F;zh-CN&#x2F;docs&#x2F;Web&#x2F;JavaScript&#x2F;Guide&#x2F;Iterators_and_Generators    ​        首先JavaScript里面的数组我们可以知道其实也是一个对象。但是为什么我们可以通过一些方法进行循环，这里就运用到了一个迭代器的方法。iterator 可迭代协议​">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-11-14T10:30:37.000Z">
<meta property="article:modified_time" content="2023-06-25T08:57:29.354Z">
<meta property="article:author" content="tallgy">
<meta property="article:tag" content="JavaScript">
<meta property="article:tag" content="迭代器">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="http://tallgy.gitee.io/2021/11/14/JavaScript/%E9%9A%8F%E7%AC%94/%E8%BF%AD%E4%BB%A3%E5%99%A8/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://tallgy.gitee.io/2021/11/14/JavaScript/%E9%9A%8F%E7%AC%94/%E8%BF%AD%E4%BB%A3%E5%99%A8/","path":"2021/11/14/JavaScript/随笔/迭代器/","title":"迭代器"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>迭代器 | tallgy's blog</title>
  




  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">tallgy's blog</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>







</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#JavaScript-%E8%BF%AD%E4%BB%A3%E5%99%A8"><span class="nav-number">1.</span> <span class="nav-text">JavaScript 迭代器</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8F%AF%E8%BF%AD%E4%BB%A3%E5%8D%8F%E8%AE%AE"><span class="nav-number">1.1.</span> <span class="nav-text">可迭代协议</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8F%AF%E8%BF%AD%E4%BB%A3%E5%AF%B9%E8%B1%A1"><span class="nav-number">1.1.1.</span> <span class="nav-text">可迭代对象</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%BF%AD%E4%BB%A3%E5%99%A8%E5%8D%8F%E8%AE%AE"><span class="nav-number">1.2.</span> <span class="nav-text">迭代器协议</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">tallgy</p>
  <div class="site-description" itemprop="description">只是一个知识的搬运工</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">107</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">32</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">74</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://tallgy.gitee.io/2021/11/14/JavaScript/%E9%9A%8F%E7%AC%94/%E8%BF%AD%E4%BB%A3%E5%99%A8/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="tallgy">
      <meta itemprop="description" content="只是一个知识的搬运工">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="tallgy's blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          迭代器
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2021-11-14 18:30:37" itemprop="dateCreated datePublished" datetime="2021-11-14T18:30:37+08:00">2021-11-14</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2023-06-25 16:57:29" itemprop="dateModified" datetime="2023-06-25T16:57:29+08:00">2023-06-25</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/JavaScript/" itemprop="url" rel="index"><span itemprop="name">JavaScript</span></a>
        </span>
          ，
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/JavaScript/%E6%A6%82%E5%BF%B5/" itemprop="url" rel="index"><span itemprop="name">概念</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="JavaScript-迭代器"><a href="#JavaScript-迭代器" class="headerlink" title="JavaScript 迭代器"></a>JavaScript 迭代器</h1><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Iterators_and_Generators</span><br></pre></td></tr></table></figure>



<p>​        首先JavaScript里面的数组我们可以知道其实也是一个对象。但是为什么我们可以通过一些方法进行循环，这里就运用到了一个迭代器的方法。iterator</p>
<h2 id="可迭代协议"><a href="#可迭代协议" class="headerlink" title="可迭代协议"></a>可迭代协议</h2><p>​        <strong>可迭代协议</strong>允许 JavaScript 对象定义或定制它们的迭代行为，例如，在一个 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/for...of"><code>for..of</code></a> 结构中，哪些值可以被遍历到。一些内置类型同时是<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Iteration_protocols#%E5%86%85%E7%BD%AE%E5%8F%AF%E8%BF%AD%E4%BB%A3%E5%AF%B9%E8%B1%A1">内置可迭代对象</a>，并且有默认的迭代行为，比如 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array"><code>Array</code></a> 或者 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Map"><code>Map</code></a>，而其他内置类型则不是（比如 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object"><code>Object</code></a>)）。</p>
<p>​        要成为<strong>可迭代</strong>对象， 一个对象必须实现 <code>**@@iterator**</code> 方法。这意味着对象（或者它<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Inheritance_and_the_prototype_chain">原型链</a>上的某个对象）必须有一个键为 <code>@@iterator</code> 的属性，可通过常量 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator"><code>Symbol.iterator</code></a> 访问该属性</p>
<p>​        简单来说就是forof进行循环的操作，会先调用一个 <code>@@iterator</code> 方法，然后使用这个方法返回的迭代器获得迭代的值。</p>
<p>​        通过这里我们就可以知道几个问题</p>
<ul>
<li>默认对象为什么不可以进行迭代，是因为对于默认是没有实现这个迭代器的。而Array和Map是默认就存在一个迭代器。</li>
<li>为什么对于数组存在empty-items，但是 forof 和 forin 为什么会不同的效果呢。就是因为forof是使用的迭代器的形式进行迭代，而forin是使用的键值对的形式进行的迭代。所以对于存在空值的数组，但是forof是通过数组的迭代器，所以还是使用的长度，而forin是使用的键值对，所以对于空值，实际上并没有迭代出来。</li>
</ul>
<h3 id="可迭代对象"><a href="#可迭代对象" class="headerlink" title="可迭代对象"></a>可迭代对象</h3><p>​        要成为<strong>可迭代</strong>对象， 一个对象必须实现 <code>**@@iterator**</code> 方法。这意味着对象（或者它<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Inheritance_and_the_prototype_chain">原型链</a>上的某个对象）必须有一个键为 <code>@@iterator</code> 的属性，可通过常量 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator"><code>Symbol.iterator</code></a> 访问该属性。</p>
<table>
<thead>
<tr>
<th align="left">属性</th>
<th align="left">值</th>
</tr>
</thead>
<tbody><tr>
<td align="left"><code>[Symbol.iterator]</code></td>
<td align="left">一个无参数的函数，其返回值为一个符合<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Iteration_protocols#%E8%BF%AD%E4%BB%A3%E5%99%A8%E5%8D%8F%E8%AE%AE">迭代器协议</a>的对象。</td>
</tr>
</tbody></table>
<p>​        此函数可以是普通函数，也可以是生成器函数，以便在调用时返回迭代器对象。 在此生成器函数的内部，可以使用<code>yield</code>提供每个条目。</p>
<h2 id="迭代器协议"><a href="#迭代器协议" class="headerlink" title="迭代器协议"></a>迭代器协议</h2><p>​        <strong>迭代器协议</strong>定义了产生一系列值（无论是有限个还是无限个）的标准方式。当值为有限个时，所有的值都被迭代完毕后，则会返回一个默认返回值。</p>
<p>​        只有实现了一个拥有以下语义（semantic）的 <code>**next()**</code> 方法，一个对象才能成为迭代器：</p>
<table>
<thead>
<tr>
<th align="left">属性</th>
<th align="left">值</th>
</tr>
</thead>
<tbody><tr>
<td align="left"><code>next</code></td>
<td align="left">一个无参数或者一个参数的函数，返回一个应当拥有以下两个属性的对象：<code>done</code>（boolean）如果迭代器可以产生序列中的下一个值，则为 <code>false</code>。（这等价于没有指定 <code>done</code> 这个属性。）如果迭代器已将序列迭代完毕，则为 <code>true</code>。这种情况下，<code>value</code> 是可选的，如果它依然存在，即为迭代结束之后的默认返回值。<code>value</code>迭代器返回的任何 JavaScript 值。done 为 true 时可省略。<code>next()</code> 方法必须返回一个对象，该对象应当有两个属性： <code>done</code> 和 <code>value</code>，如果返回了一个非对象值（比如 <code>false</code> 或 <code>undefined</code>），则会抛出一个 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/TypeError"><code>TypeError</code></a> 异常（<code>&quot;iterator.next() returned a non-object value&quot;</code>）。</td>
</tr>
</tbody></table>
<p>​        查看一个内置的可迭代对象</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">let someString = &quot;hi&quot;;</span><br><span class="line">typeof someString[Symbol.iterator];          // &quot;function&quot;</span><br><span class="line"></span><br><span class="line">let iterator = someString[Symbol.iterator]();</span><br><span class="line">iterator + &quot;&quot;;                   // &quot;[object String Iterator]&quot;</span><br><span class="line"></span><br><span class="line">iterator.next();                         // &#123; value: &quot;h&quot;, done: false &#125;</span><br><span class="line">iterator.next();                         // &#123; value: &quot;i&quot;, done: false &#125;</span><br><span class="line">iterator.next();                 // &#123; value: undefined, done: true &#125;</span><br></pre></td></tr></table></figure>



<p>​        自己提供一个@@iterator 方法，方法需要能够使用next方法。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">// 必须构造 String 对象以避免字符串字面量 auto-boxing</span><br><span class="line">var someString = new String(&quot;hi&quot;);</span><br><span class="line">someString[Symbol.iterator] = function() &#123;</span><br><span class="line">  return &#123; // 只返回一次元素，字符串 &quot;bye&quot;，的迭代器对象</span><br><span class="line">    next: function() &#123;	</span><br><span class="line">      if (this._first) &#123;</span><br><span class="line">        this._first = false;</span><br><span class="line">        return &#123; value: &quot;bye&quot;, done: false &#125;;</span><br><span class="line">      &#125; else &#123;</span><br><span class="line">        return &#123; done: true &#125;;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    _first: true</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>​        通过*<strong>生成器函数*</strong> 也可以生成这个效果。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">var myIterable = &#123;&#125;;</span><br><span class="line">myIterable[Symbol.iterator] = function* () &#123;</span><br><span class="line">    yield 1;</span><br><span class="line">    yield 2;</span><br><span class="line">    yield 3;</span><br><span class="line">&#125;;</span><br><span class="line">[...myIterable]; // [1, 2, 3]</span><br></pre></td></tr></table></figure>



<p>​        一个简单的示例。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line">let o = &#123;</span><br><span class="line">  a: 1,</span><br><span class="line">  b: 2,</span><br><span class="line">  x: 3</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">这个是使用的生成器语法进行的操作。</span><br><span class="line">个人建议使用生成器函数进行操作，生成器的语法非常合适这个迭代器。如果不使用生成器的语法，会比较复杂。</span><br><span class="line">o[Symbol.iterator] = function* () &#123;</span><br><span class="line">  let keys = Object.keys(this);</span><br><span class="line">  for (const keysKey in keys) &#123;</span><br><span class="line">    yield this[keys[keysKey]];</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">这里是一个没有使用生成器的语法，所以对于返回值，需要有一个next函数进行调用。然后，调用之后会返回一个值，然后如何解决是否返回结束，行为就是一个index进行存储，但是如果先进行了index的修改，那么return的时候也要进行一次修改，所以会比较麻烦。</span><br><span class="line">o[Symbol.iterator] = function () &#123;</span><br><span class="line">  let keys = Object.keys(this);</span><br><span class="line">  let obj = this;</span><br><span class="line"></span><br><span class="line">  return &#123;</span><br><span class="line">    next: function () &#123;</span><br><span class="line">      if (keys[this.index]) &#123;</span><br><span class="line">        //最终方式</span><br><span class="line">        return &#123; value: obj[keys[this.index++]], done: false &#125;;</span><br><span class="line">        </span><br><span class="line">        //++this.index;</span><br><span class="line">        //return &#123; value: obj[keys[this.index-1]], done: false &#125;;</span><br><span class="line">        </span><br><span class="line">        //	</span><br><span class="line">        //return &#123; value: obj[keys[this.index]], done: false &#125;;</span><br><span class="line">        </span><br><span class="line">        //	通过这里我们也 知道了，++会先于 &amp;&amp;||逻辑运算符。</span><br><span class="line">        //return this.index++ || console.log(this.index) &amp;&amp; &#123; value: obj[keys[this.index]], done: false &#125;;</span><br><span class="line">      &#125; else &#123;</span><br><span class="line">        return &#123; done: true &#125;;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    index: 0</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>​        通过这个方法可以取出迭代器对象并且使用next()获取下一个迭代的值。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">let oo = o[Symbol.iterator]();</span><br><span class="line">console.log(oo.next());</span><br></pre></td></tr></table></figure>



<p>生成器对象既是一个迭代器，也是一个可迭代的对象。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">let generator = function* ()&#123;</span><br><span class="line">  yield 1;</span><br><span class="line">  yield 2;</span><br><span class="line">  yield 3;</span><br><span class="line">&#125;();</span><br><span class="line"></span><br><span class="line">console.log(typeof generator.next);</span><br><span class="line">// 返回&quot;function&quot;, 因为有一个next方法，所以这是一个迭代器</span><br><span class="line">迭代器就是存在了next方法的一个对象，next方法的返回值为value和done</span><br><span class="line"></span><br><span class="line">console.log(typeof generator[Symbol.iterator]);</span><br><span class="line">// 返回&quot;function&quot;, 因为有一个@@iterator方法，所以这是一个可迭代对象</span><br><span class="line">可迭代对象，意思就是说这个是可以使用迭代器的，可以使用forof方法。简单来说就是这个方法内部实现了 [Symbol.iterator] 函数。</span><br><span class="line"></span><br><span class="line">console.log(generator[Symbol.iterator]() === generator);</span><br><span class="line">// 返回true, 因为@@iterator方法返回自身（即迭代器），所以这是一个格式良好的可迭代对象</span><br><span class="line">首先，我们知道这是一个可迭代对象，也是一个迭代器，意思就是说，这个迭代器的内部也存在一个迭代器。一个是它本身的任务就是一个迭代器，另一个是它作为一个可迭代对象，它存在一个内部的迭代器，然后这里的意思就是说可迭代对象的迭代器方法和它自身是相等的。</span><br><span class="line">感觉就像是一个普通函数返回的对象里面有一个next方法和一个[Symbol.iterator]方法，然后这个Symbol.iterator方法是直接返回自身。所以就是迭代器的迭代器方法返回为自身。</span><br><span class="line"></span><br><span class="line">console.log([...generator]);</span><br><span class="line">// 返回[1, 2, 3]</span><br><span class="line"></span><br><span class="line">console.log(Symbol.iterator in generator)</span><br><span class="line">// 返回true, 因为@@iterator方法是generator的一个属性</span><br></pre></td></tr></table></figure>

<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line">let o = &#123;</span><br><span class="line">  a: 1,</span><br><span class="line">  b: 2,</span><br><span class="line">  x: 3</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// o[Symbol.iterator] = function* () &#123;</span><br><span class="line">//   let keys = Object.keys(this);</span><br><span class="line">//</span><br><span class="line">//   for (const keysKey in keys) &#123;</span><br><span class="line">//     yield this[keys[keysKey]];</span><br><span class="line">//   &#125;</span><br><span class="line">// &#125;;</span><br><span class="line"></span><br><span class="line">o[Symbol.iterator] = function () &#123;</span><br><span class="line">  let keys = Object.keys(this);</span><br><span class="line">  let obj = this;</span><br><span class="line">  return &#123;</span><br><span class="line">    next: function () &#123;</span><br><span class="line">      if (keys[this.index]) &#123;</span><br><span class="line">        return &#123; value: obj[keys[this.index++]], done: false &#125;;</span><br><span class="line">      &#125; else &#123;</span><br><span class="line">        return &#123; done: true &#125;;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    [Symbol.iterator]: function () &#123;</span><br><span class="line">      return this;</span><br><span class="line">    &#125;,</span><br><span class="line">    index: 0</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">let generator = function* ()&#123;</span><br><span class="line">  yield 1;</span><br><span class="line">  yield 2;</span><br><span class="line">  yield 3;</span><br><span class="line">&#125;();</span><br><span class="line"></span><br><span class="line">console.log(typeof generator.next);</span><br><span class="line"></span><br><span class="line">let g = o[Symbol.iterator]();</span><br><span class="line">console.log(typeof g.next);</span><br><span class="line">// 返回&quot;function&quot;, 因为有一个next方法，所以这是一个迭代器</span><br><span class="line"></span><br><span class="line">console.log(typeof generator[Symbol.iterator]);</span><br><span class="line">console.log(typeof g[Symbol.iterator])</span><br><span class="line">// 返回&quot;function&quot;, 因为有一个@@iterator方法，所以这是一个可迭代对象</span><br><span class="line"></span><br><span class="line">console.log(generator[Symbol.iterator]() === generator);</span><br><span class="line">console.log(g[Symbol.iterator]() === g);</span><br><span class="line">// 返回true, 因为@@iterator方法返回自身（即迭代器），所以这是一个格式良好的可迭代对象</span><br><span class="line"></span><br><span class="line">console.log([...generator]);</span><br><span class="line">// 返回[1, 2, 3]</span><br><span class="line"></span><br><span class="line">console.log(Symbol.iterator in generator)</span><br><span class="line">console.log(Symbol.iterator in g)</span><br><span class="line">// 返回true, 因为@@iterator方法是generator的一个属性</span><br></pre></td></tr></table></figure>


    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/JavaScript/" rel="tag"># JavaScript</a>
              <a href="/tags/%E8%BF%AD%E4%BB%A3%E5%99%A8/" rel="tag"># 迭代器</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2021/11/14/JavaScript/%E6%96%B9%E6%B3%95/%E6%95%B0%E7%BB%84%E7%9A%84%E6%96%B9%E6%B3%95/" rel="prev" title="数组的方法">
                  <i class="fa fa-chevron-left"></i> 数组的方法
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2021/11/16/Vue/Vue%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F/" rel="next" title="Vue生命周期">
                  Vue生命周期 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">tallgy</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  





  





</body>
</html>
